﻿﻿﻿﻿using System.Configuration;
using System.Data;
using System.IO;
using System.Threading;
using System.Windows;
using LibVLCSharp.Shared;
using LibVLCSharp.WPF;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using VideoClient;
using vlcplay.Logging;
using vlcplay.ViewModels;

namespace vlcplay;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private static Mutex? _mutex;
    public static IServiceProvider ServiceProvider { get; private set; } = null!; // Initialize with null forgiving operator or ensure in constructor
    public ILogger<App> Logger { get; private set; } = null!; // Initialize with null forgiving operator or ensure in constructor
    protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += (s, ex) =>
        {
            // 写日志
            var logger = ServiceProvider.GetService<ILogger<App>>();
            logger?.LogError(ex.ExceptionObject as Exception, "全局未捕获异常");
        };

        bool createdNew;
        _mutex = new Mutex(true, "vlcplay_single_instance_mutex", out createdNew);

        if (!createdNew)
        {
            // 已有实例在运行，直接退出
            MessageBox.Show("程序已在运行中，不能重复打开。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            Environment.Exit(0);
            return;
        }

        var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "xhvideoplay");
        Directory.CreateDirectory(logDir);
        var services = new ServiceCollection();
        // 添加日志服务
        services.AddLogging(builder =>
        {
            builder.ClearProviders();
            builder.AddProvider(new FileLoggerProvider(logDir)); // Pass null is allowed by constructor, but better to use the overload without filter if null
            builder.AddConsole(); // 可选：控制台也输出一份
        });
        // 注册 XhVideoClient 为单例
        services.AddSingleton<XhVideoClient>();
        // 注册 MainViewModel
        services.AddTransient<MainViewModel>();
        // 注册你的服务或窗口
        services.AddTransient<MainWindow>();
        services.AddTransient<LoginWindow>();
        // services.AddTransient<MaximizedVideoWindow>(); // Not strictly needed if always created with new() and logger passed


        ServiceProvider = services.BuildServiceProvider();

        // 初始化日志器
        Logger = ServiceProvider.GetRequiredService<ILogger<App>>();
        Logger.LogInformation("应用程序启动");
        Core.Initialize();
        base.OnStartup(e);

    }
}
